<?php
require_once( 'config.php');
require_once( 'server_request.php' );
require_once( 'commands.php' );

$sCommand = $_GET['command'];
//$sCommand = 'rename';

$oResponse = new ServerResponse();


class RequestDispatcher
{
	private $aCallbacks;
	
	public function registerCommand( $sCommand, $fCallback )
	{
		if ( !is_callable( $fCallback ) )
		{
			throw new Exception( 'Cannot register command "'.$sCommand.'"because the callback is not a function' );
		}
		
		$this->aCallbacks[ $sCommand ] = $fCallback;
	}
	
	public function __construct()
	{
		$this->registerCommand( 'create_file', 'commandCreateFile' );
		$this->registerCommand( 'create_dir', 'commandCreateDir' );
		$this->registerCommand( 'load_file', 'commandLoadFile' );
    $this->registerCommand( 'remove_file_or_dir', 'commandRemoveFileOrDir' );
		$this->registerCommand( 'rename', 'commandRename' );
		$this->registerCommand( 'sync_project', 'commandSynchronizeProject' );
    $this->registerCommand( 'upload_content', 'commandUploadContentFile' );
	}
	
	public function processRequest( $oResponse, $sCommand )
	{
		if ( isset( $this->aCallbacks[ $sCommand ] ) )
		{
			if ( is_callable( $this->aCallbacks[ $sCommand ] ) )
				$this->aCallbacks[ $sCommand ]( $oResponse );
			else
				$oResponse->error( 'The callback associate to the command "'.$sCommand.'" is not a function (not callable)' );
		}
		else
		{
			$oResponse->error( 'Unknown command : '.$sCommand );
		}
	}
}

ob_start();

// Create the unique request dispatcher if needed
try 
{
	if ( !isset( $_SESSION[ 'oRequestDispatcher' ] ) )
		$_SESSION[ 'oRequestDispatcher'] = new RequestDispatcher();
	
} catch ( Exception $e )
{
	$oResponse->exception( $e );
}

// Process request
try 
{
	$_SESSION[ 'oRequestDispatcher']->processRequest( $oResponse, $sCommand );
	
} catch ( Exception $e )
{
	$oResponse->exception( $e );
}

$stdout = ob_get_contents();

ob_end_clean();

if ( $stdout != "" )
{
	$oResponse->error( $stdout );
}

echo( $oResponse->getResponse() );

?>